<?php
namespace core;
use core\lib\log;
class MyFrame{
	public static $classMap = array();
	public $assign_data = array();
	
	public static function run(){
		//日志启动
		log::init();
		$route = new \core\lib\route();
		define('CONTROLLER_NAME',$route->controller);
		define('ACTION_NAME',$route->action);
		$controllerFile = APP.'/controller/'.CONTROLLER_NAME.'Controller.php';
		$controllerClass= '\\'.MODULE.'\controller\\'.CONTROLLER_NAME.'Controller';
		if(is_file($controllerFile)){
			include $controllerFile;
			$controller = new $controllerClass();
			$actionName =  ACTION_NAME;
			$controller->$actionName();
			log::log('控制器为'.CONTROLLER_NAME);
			log::log('操作名为'.ACTION_NAME);
		}else{
			throw new \Exception('找不到控制器');
		}
	}
	
	//自动加载类
	public static function load($class){
		//p($class);
		//避免重复加载类
		if(isset(self::$classMap[$class]) || strpos($class,'app') !== false){
			return true;
		}else{
			//自动加载类库,'\'表示转义，所以使用'\\'
			$class = str_replace('\\','/',$class);
			$file = MYFRAME.'/'.$class.'.php';
			//判断文件是否存在                    
			if(is_file($file)){
				include $file;
				self::$classMap[$class] = $class;
			}else{
				return false;
			}
		}		
	} 

	public function assign($name,$value){
		$this->assign_data[$name] = $value;
	}

	public function display($display){
		$file = APP.'/view/'.$display;
		if(is_file($file)){
			//函数从数组中将变量导入到当前的符号表。
			//extract($this->assign_data);
			//include $file;
			$display_list = explode('/',$display);
			$path = APP.'/view/'.$display_list[0];
			\Twig_Autoloader::register();
			$loader =  new \Twig_Loader_Filesystem($path);
			$twig = new \Twig_Environment($loader, array(
			    'cache' => MYFRAME.'/runtime',
			    'debug' => DEBUG,
			));
			$template = $twig->loadTemplate($display_list[1]);
			$template->display($this->assign_data ? $this->assign_data :[] );
			
		}
	}
}

